package com.ocom.nettyxf.service.impl;

import cn.hutool.core.util.HexUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ocom.common.entity.card.EntityXfMealTime;
import com.ocom.common.resp.RespMachMessage;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.CommonUtil;
import com.ocom.common.utils.NumConvertUtil;
import com.ocom.common.vo.pay.KeySecret;
import com.ocom.common.vo.pay.MachMerchPointInfoVo;
import com.ocom.common.vo.pyhandle.GetMachParaVo;
import com.ocom.nettyxf.client.AiotFeignService;
import com.ocom.nettyxf.client.PayHandleFeignService;
import com.ocom.nettyxf.client.SrvpAccessDeviceClient;
import com.ocom.nettyxf.resp.MachUpdate;
import com.ocom.nettyxf.ropo.TcpServiceRopo;
import com.ocom.nettyxf.service.XfService;
import com.ocom.nettyxf.vo.*;
import com.ocom.redis.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: TODO
 * @Author: 朱晖
 * @Date: 2022/10/21
 **/

@Slf4j
@Service
@Resource
public class XfServerImpl implements XfService {


	@Resource
	private RedisUtil redisUtil;

	@Autowired
	private PayHandleFeignService payHandleFeignService;

	@Autowired
	private AiotFeignService aiotFeignService;

	@Autowired
	private SrvpAccessDeviceClient accessDeviceClient;


	@Override
	public byte[] heartbeat(TcpServiceRopo tcpServiceRopo) throws Exception {
//		log.info("心跳："+tcpServiceRopo.toString());

		//要返回的对象
		TcpServiceRopo resp = new TcpServiceRopo();
		//赋返回值  全是16进制字符串
		resp.setMachId(tcpServiceRopo.getMachId());
		resp.setEdition(tcpServiceRopo.getEdition());
		resp.setType(tcpServiceRopo.getType());
		resp.setPackageNum(tcpServiceRopo.getPackageNum());
		resp.setCommandType(tcpServiceRopo.getCommandType());

		HeartbeatVo heartbeatVo = new HeartbeatVo();


		//商户编号
		Long companyId = ((Integer) redisUtil.hmGet("tcpXfMach:" + tcpServiceRopo.getMachId(), "companyId")).longValue();
		Integer saasNo = (Integer) redisUtil.hmGet("tcpXfMach:" + tcpServiceRopo.getMachId(), "saasNo");

		//平台编号为1按照本平台走
		if (saasNo == 1) {
			//从srvpaccess查询更新标识
			RespMachMessage srvpaccessGetDeviceFlag = payHandleFeignService.getDeviceFlag(companyId, tcpServiceRopo.getMachId(), "");

			if (srvpaccessGetDeviceFlag.getCode().equals("0000")) {
				JSONObject jsonSrvpaccess = JSON.parseObject(JSON.toJSONString(srvpaccessGetDeviceFlag.getData()));
				Integer paramUpdate = jsonSrvpaccess.getInteger("paramUpdate");
				Integer fkUpdate = jsonSrvpaccess.getInteger("fkUpdate");
				Integer meal = jsonSrvpaccess.getInteger("meal");
				Integer zhxySecret = jsonSrvpaccess.getInteger("zhxySecret");
				Integer listUpdate = jsonSrvpaccess.getInteger("listUpdate");
				if (paramUpdate > 0) {
					heartbeatVo.setParamUpdate("01");
				}
				if (fkUpdate > 0) {
					heartbeatVo.setFk("01");
				}
				if (listUpdate > 0) {
					heartbeatVo.setWhiteList("01");
				}
				if (meal > 0) {
					heartbeatVo.setMean("01");
				}
				if (zhxySecret > 0) {
					heartbeatVo.setSecret("01");
				}
				RespMachMessage resGetDeviceFlag = aiotFeignService.getDeviceFlag(tcpServiceRopo.getMachId(), "");

				if (resGetDeviceFlag.getCode().equals("0000")) {
					JSONObject jsonGetDeviceFlag = JSON.parseObject(JSON.toJSONString(resGetDeviceFlag.getData()));
					Integer firmwareUpdate = jsonGetDeviceFlag.getInteger("firmwareUpdate");
					if (firmwareUpdate > 0) {
						heartbeatVo.setMachUpdate("01");
					}
					//测试
//					heartbeatVo.setParamUpdate("01");
//					heartbeatVo.setFk("00");
//					heartbeatVo.setWhiteList("01");

					resp.setCommandParam(heartbeatVo.getHexStr());

					log.info("Tcp_心跳-返回【{}】 【{}】", heartbeatVo, resp);
					String rc = resp.getHexStr();
					return HexUtil.decodeHex(rc);
				} else {
					resp.setCommandParam("5000",4,resGetDeviceFlag.getMsg());
					String rc = resp.getHexStr();
					return HexUtil.decodeHex(rc);
				}
			} else {
				resp.setCommandParam("0003",4,srvpaccessGetDeviceFlag.getMsg());
				String rc = resp.getHexStr();
				return HexUtil.decodeHex(rc);
			}
		} else {
			resp.setCommandParam("0401",4,"saasNo未配置");
			String rc = resp.getHexStr();
			return HexUtil.decodeHex(rc);
		}

	}

	@Override
	public byte[] paramUpdate(TcpServiceRopo tcpServiceRopo) throws Exception {
		log.info("参数更新：" + tcpServiceRopo.toString());
		//要返回的对象
		TcpServiceRopo resp = new TcpServiceRopo();
		//赋返回值  全是16进制字符串
		resp.setMachId(tcpServiceRopo.getMachId());
		resp.setEdition(tcpServiceRopo.getEdition());
		resp.setType(tcpServiceRopo.getType());
		resp.setPackageNum(tcpServiceRopo.getPackageNum());
		resp.setCommandType(tcpServiceRopo.getCommandType());

		ParamVo paramVo = new ParamVo();

		String machno = tcpServiceRopo.getMachId();
		try {
			//商户编号
			Long companyId = ((Integer) redisUtil.hmGet("tcpXfMach:" + tcpServiceRopo.getMachId(), "companyId")).longValue();
			Integer saasNo = (Integer) redisUtil.hmGet("tcpXfMach:" + tcpServiceRopo.getMachId(), "saasNo");

			//平台编号为1按照本平台走
			if (saasNo == 1) {
				Map<String, Object> getMachPara = new HashMap<>();
				getMachPara.put("companyId", companyId);
				getMachPara.put("machNo", machno);
				//从srvpaccess查询更新标识
				Result srvpaccessGetDeviceFlag = payHandleFeignService.getMachPara(getMachPara);
				if (srvpaccessGetDeviceFlag.getCode() == 200) {
					JSONObject jsonGetDeviceFlag = JSON.parseObject(JSON.toJSONString(srvpaccessGetDeviceFlag.getData()));

					if (!CommonUtil.isNull(jsonGetDeviceFlag.getString("jobId"))) {
						paramVo.setJobId(Long.toHexString(Long.valueOf(jsonGetDeviceFlag.getString("jobId"))));  //12位
					}

					Map<String, Integer> payParam = JSON.parseObject(JSON.toJSONString(jsonGetDeviceFlag.get("heartData")), Map.class);
					Map<String, Integer> machParam = JSON.parseObject(JSON.toJSONString(jsonGetDeviceFlag.get("machineData")), Map.class);
					List<EntityXfMealTime> mealParam = JSON.parseArray(JSON.toJSONString(jsonGetDeviceFlag.get("meal")), EntityXfMealTime.class);

					paramVo.getParamPayVo().setPayTime(NumConvertUtil.IntToHexStringNum(payParam.get("payTimes"), 2));
				//	paramVo.getParamPayVo().setPayInterval(NumConvertUtil.IntToHexStringNum(payParam.get("payInterval"), 2));
					paramVo.getParamPayVo().setPayInterval("05");
					paramVo.getParamPayVo().setCancelFlag(NumConvertUtil.IntToHexStringNum(payParam.get("cancelFlag"), 2));
					paramVo.getParamPayVo().setHeartBeatNum(NumConvertUtil.IntToHexStringNum(payParam.get("heartBeatNum"), 2));

					paramVo.getParamMachVo().setConsType(NumConvertUtil.IntToHexStringNum(machParam.get("consType"), 2));
					paramVo.getParamMachVo().setDeviceMode(NumConvertUtil.IntToHexStringNum(machParam.get("deviceMode"), 2));

					Result result1 = payHandleFeignService.GetMerchInfoByMachNo(companyId, tcpServiceRopo.getMachId());

					if (result1.getCode() == 200) {
						MachMerchPointInfoVo machMerchPointInfoVo = JSON.parseObject(JSON.toJSONString(result1.getData()), MachMerchPointInfoVo.class);
						paramVo.getParamMachVo().setMerchName(NumConvertUtil.toGBK(machMerchPointInfoVo.getMerchName()));
						paramVo.getParamMachVo().setMachName(NumConvertUtil.toGBK(machMerchPointInfoVo.getDeviceName()));
					}

					List<MealVo> mealVoList = new ArrayList<>();

					GetMachParaVo getMachParaVo = new GetMachParaVo();
					getMachParaVo.setCompanyId(companyId);
					getMachParaVo.setMachNo(machno);
					Result result4 = payHandleFeignService.getMachParaTwo(getMachParaVo);

					if(result4.getCode() == 200){
						JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(result4.getData()),JSONObject.class);
						List<JSONObject> parseMapArray = JSON.parseArray(JSON.toJSONString(jsonObject.get("mealPara")), JSONObject.class);
						if(parseMapArray!=null){
							for (JSONObject jsonObject1 : parseMapArray) {
								if (CommonUtil.isNull(jsonObject1.getString("beginTime"))
										|| CommonUtil.isNull(jsonObject1.getString("endTime"))) {
									continue;
								}
								MealVo mealVo = new MealVo();
//								mealVo.setMealName(NumConvertUtil.toGBK(jsonObject1.getString("")));
								mealVo.setMealNo(NumConvertUtil.IntToHexStringNum(jsonObject1.getInteger("mealNo"), 2));
								mealVo.setBeginTime(jsonObject1.getString("beginTime").substring(0, 5).replace(":", ""));
								mealVo.setEndTime(jsonObject1.getString("endTime").substring(0, 5).replace(":", ""));
								if(jsonObject1.getInteger("cosumerMode") != null){
									mealVo.setCosumerMode(NumConvertUtil.IntToHexStringNum(jsonObject1.getInteger("cosumerMode"), 2));
								}
								if(jsonObject1.getInteger("mealMoney") != null){
									mealVo.setMealMoney(NumConvertUtil.IntToHexStringNum(jsonObject1.getInteger("mealMoney"), 8));
								}
								if(jsonObject1.getString("AccountTypes") != null &&  !jsonObject1.getString("AccountTypes").equals("")){
									String[] types = jsonObject1.getString("AccountTypes").split(",");
									String hexType = "";
									for (String  typeIn :types){
										if(CommonUtil.isNull(typeIn)) continue;
										hexType += NumConvertUtil.IntToHexStringNum(Integer.valueOf(typeIn), 2);
									}
									mealVo.setAccountType(hexType);
								}
								if(jsonObject1.getInteger("voucherMode") != null){
									mealVo.setVoucherMode(NumConvertUtil.IntToHexStringNum(jsonObject1.getInteger("voucherMode"), 2));
								}

								mealVoList.add(mealVo);
							}
						}

					}

//					for (EntityXfMealTime entityXfMealTime : mealParam) {
//						if (CommonUtil.isNull(entityXfMealTime.getBeginTime())
//								|| CommonUtil.isNull(entityXfMealTime.getEndTime())) {
//							continue;
//						}
//						MealVo mealVo = new MealVo();
//						mealVo.setMealName(NumConvertUtil.toGBK(entityXfMealTime.getMealName()));
//						mealVo.setMealNo(NumConvertUtil.IntToHexStringNum(Integer.valueOf(entityXfMealTime.getMealNo()), 2));
//						mealVo.setBeginTime(entityXfMealTime.getBeginTime().substring(0, 5).replace(":", ""));
//						mealVo.setEndTime(entityXfMealTime.getEndTime().substring(0, 5).replace(":", ""));
//						mealVoList.add(mealVo);
//					}

					paramVo.getParamMachVo().setMealVoList(mealVoList);


					log.info("机器参数 实体【{}】", paramVo);

					resp.setCommandParam(paramVo.getHexStr());
					String rc = resp.getHexStr();

					log.info("Tcp_paramUpdate-返回【{}】 【{}】", tcpServiceRopo, paramVo);

					return HexUtil.decodeHex(rc);
				} else {
					resp.setCommandParam("0003",4,srvpaccessGetDeviceFlag.getMsg());
					String rc = resp.getHexStr();
					return HexUtil.decodeHex(rc);
				}
			} else {
				resp.setCommandParam("0401",4,"saasNo未配置");
				String rc = resp.getHexStr();
				return HexUtil.decodeHex(rc);
			}
		} catch (Exception e) {
			log.info("异常 【{}】", e);
			resp.setCommandParam("5000",4,"系统异常");
			String rc = resp.getHexStr();
			return HexUtil.decodeHex(rc);
		}

	}

	@Override
	public byte[] paramUpdateResult(TcpServiceRopo tcpServiceRopo) throws Exception {
		//要返回的对象
		TcpServiceRopo resp = new TcpServiceRopo();
		//赋返回值  全是16进制字符串
		resp.setMachId(tcpServiceRopo.getMachId());
		resp.setEdition(tcpServiceRopo.getEdition());
		resp.setType(tcpServiceRopo.getType());
		resp.setPackageNum(tcpServiceRopo.getPackageNum());
		resp.setCommandType(tcpServiceRopo.getCommandType());

		//00成功 01失败
		String JobId = tcpServiceRopo.getCommandParam().substring(0, 12);

		if (!tcpServiceRopo.getCommandParam().endsWith("00")) {
			resp.setCommandParam("0000");
			String rc = resp.getHexStr();
			return HexUtil.decodeHex(rc);
		}

		//商户编号
		Long companyId = ((Integer) redisUtil.hmGet("tcpXfMach:" + tcpServiceRopo.getMachId(), "companyId")).longValue();
		Integer saasNo = (Integer) redisUtil.hmGet("tcpXfMach:" + tcpServiceRopo.getMachId(), "saasNo");


		Map<String, Object> getMachPara = new HashMap<>();
		getMachPara.put("companyId", companyId);
		getMachPara.put("machNo", tcpServiceRopo.getMachId());
		Long jobId2 = Long.parseLong(JobId, 16);
		getMachPara.put("jobId", jobId2);
		Result srvpaccessGetDeviceFlag = payHandleFeignService.changeMachParaState(getMachPara);

		if (srvpaccessGetDeviceFlag.getCode() != 200) {
			log.info("参数更新  调用changeMachParaState 失败 参数 【{}】 响应【{}】", tcpServiceRopo, srvpaccessGetDeviceFlag);
			resp.setCommandParam("5000",4,srvpaccessGetDeviceFlag.getMsg());
			String rc = resp.getHexStr();
			return HexUtil.decodeHex(rc);
		}

		JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(srvpaccessGetDeviceFlag.getData()));

		ParamResultVo paramResultVo = new ParamResultVo();

		paramResultVo.setUpdate(NumConvertUtil.IntToHexStringNum(jsonObject.getInteger("updataFlag"), 2));

		log.info("Tcp_paramUpdateResult-返回【{}】 【{}】", tcpServiceRopo, paramResultVo);

		resp.setCommandParam(paramResultVo.getHexStr());
		String rc = resp.getHexStr();
		return HexUtil.decodeHex(rc);
	}

	@Override
	public byte[] machUpdate(TcpServiceRopo tcpServiceRopo) throws Exception {
		//要返回的对象
		TcpServiceRopo resp = new TcpServiceRopo();
		//赋返回值  全是16进制字符串
		resp.setMachId(tcpServiceRopo.getMachId());
		resp.setEdition(tcpServiceRopo.getEdition());
		resp.setType(tcpServiceRopo.getType());
		resp.setPackageNum(tcpServiceRopo.getPackageNum());
		resp.setCommandType(tcpServiceRopo.getCommandType());

		MachUpdateVo machUpdateVo = new MachUpdateVo();

		Long companyId = ((Integer) redisUtil.hmGet("tcpXfMach:" + tcpServiceRopo.getMachId(), "companyId")).longValue();

		String packNo = tcpServiceRopo.getCommandParam();

		RespMachMessage respMachMessage1 = aiotFeignService.getXfBinData(companyId, tcpServiceRopo.getMachId(), NumConvertUtil.HexStringToInt(packNo));//
//		log.info("获取到的二进制升级数组 respMachMessage1:" + respMachMessage1);
//        System.out.println(respMachMessage1);
		if (!respMachMessage1.getCode().equals("0000")) {
			resp.setCommandParam(respMachMessage1.getCode(),4,respMachMessage1.getMsg());
			String rc = resp.getHexStr();
			return HexUtil.decodeHex(rc);
		}

		MachUpdate machUpdate = JSON.parseObject(JSON.toJSONString(respMachMessage1.getData()), MachUpdate.class);
//		System.out.println("machUpdate:" + machUpdate);

		String jobId = NumConvertUtil.IntToHexStringNum(machUpdate.getJobId(), 12);

		machUpdateVo.setJobId(jobId);

		String packSize = NumConvertUtil.IntToHexStringNum(512, 4);

		machUpdateVo.setPackageContent(packSize);

//		log.info("machUpdate:" + machUpdate);
		//固件分为多组下传，第一组为新代码存放地址（4字节）和新代码长度（4字节）；第二组开始为固件代码。
		if (packNo.equals("0000")) {
			//响应结果  6个字节
			String param = "0000" + jobId + "0000" + packSize + "00000000";
			StringBuilder stringBuilder = new StringBuilder(param);
			String size3 = NumConvertUtil.IntToHexStringNum(machUpdate.getBinBlockNum(), 8);
			stringBuilder.append(size3);
			resp.setCommandParam(stringBuilder.toString());
			String rc = resp.getHexStr();
			return HexUtil.decodeHex(rc);
		}
		if (machUpdate.getBlockSize() == null) {
			resp.setCommandParam("0003",4,"获取到空包");
			String rc = resp.getHexStr();
			return HexUtil.decodeHex(rc);
		}


		String HexPass = "38517D798DB7DD779ECEBA5D6199FD9C661044CD35842CA6E0035F0089531E95361400514E5DC797D84F9201EA135E8716D8B80EFA1272B1764FAB2120BCC094B98C9975773C57B829CB00B82F0A61C62609A61BC73A8117CFCA3C262AB2A9759EC6A42F87431975AA5391A57B25AD8582F77F1DB4EA19006497D69063AFF29AC3F948405881043C4995E440BEAADAF7516BD16389F8408C1CDC5522414C44316764572BFDC27C608CD3522FCF97C5C12595E1EDCA9D712D5101EB6556206D319218FB1903D229FECE59D11E9FB6C52798800D63EAF6A493870FBCBA191CBFF121F4B599EC3EF5A0D1890694058768F7A23BE255D46E05ACC6B14A25DC7C5D8A8C9E1F58BAD40ECDC519DDED5C9CA5D61D4087A47073343B2AC3C4408C37A278E6EEF409C63E9992B7F49FF6DBA8D64A41B6FF5A0DFE7653152C3E524E6704BBCEC431F258D883ABD4B84179ABE3785320E9EDD2D900BC2FD93551A5C09AFFE29EC6A42F87431975AA5391A57B25AD85DB7FCBC0C6D342D3FA9A61D1599D5A92A188559ACA991D13675B867E61208153603E93D3CD4DEA8F957FA35DB31BF137B76A2534A314BC1B110A3B134144294D3C32239FABF583A24874AD167D078F1A5465CFCBD3709A238FE305DF2109DE6D7185EED07A589F935B646D6DE0C4DDADB2AF39737B80D35FADAD3CE11729B7A9F5A86715C7091663C4571CBCA84979F1";
		byte[] HexPassByte = NumConvertUtil.hexStringToByte(HexPass);
		//加密 异或
		StringBuilder newStr = new StringBuilder();
		int i = 0;
		if (machUpdate.getBlockSize() > 0) {
			for (String str : machUpdate.getBlockData()) {
				newStr.append(str);
				i++;
			}
		}
		if (i < 512) {
//			stringBuilder.replace(20,24,NumConvertUtil.IntToHexStringNum(i,4));
			machUpdateVo.setPackageContent(NumConvertUtil.IntToHexStringNum(i, 4));
			for (int j = 512 - i; j > 0; j--) {
				newStr.append("00");
			}
		}

		byte[] newStrByte = NumConvertUtil.hexStringToByte(newStr.toString());

		for (int k = 0; k < 512; k++) {
			newStrByte[k] = (byte) (newStrByte[k] ^ HexPassByte[k]);
		}

//		System.out.println(NumConvertUtil.bytesToHexString(newStrByte));

		machUpdateVo.setPackageNum(packNo);
		machUpdateVo.setData(NumConvertUtil.bytesToHexString(newStrByte));

		resp.setCommandParam(machUpdateVo.getHexStr());
		String rc = resp.getHexStr();
		return HexUtil.decodeHex(rc);
	}

	@Override
	public byte[] machUpdateResult(TcpServiceRopo tcpServiceRopo) throws Exception {
		//要返回的对象
		TcpServiceRopo resp = new TcpServiceRopo();
		//赋返回值  全是16进制字符串
		resp.setMachId(tcpServiceRopo.getMachId());
		resp.setEdition(tcpServiceRopo.getEdition());
		resp.setType(tcpServiceRopo.getType());
		resp.setPackageNum(tcpServiceRopo.getPackageNum());
		resp.setCommandType(tcpServiceRopo.getCommandType());

		MachUpdateResultVo machUpdateResultVo = new MachUpdateResultVo();

		Long companyId = ((Integer) redisUtil.hmGet("tcpXfMach:" + tcpServiceRopo.getMachId(), "companyId")).longValue();

		String recode = tcpServiceRopo.getCommandParam().substring(0, 12);

		if (!tcpServiceRopo.getCommandParam().startsWith("00", 12)) {
			resp.setCommandParam("5000",4,"未以00开头");
			String rc = resp.getHexStr();
			return HexUtil.decodeHex(rc);
		}

		RespMachMessage respMachMessage1 = aiotFeignService.changeXfBinDataState(companyId, tcpServiceRopo.getMachId(), NumConvertUtil.HexStringToInt(recode));
		log.info("固件续传通知【{}】", respMachMessage1);
		if (!respMachMessage1.getCode().equals("0000")) {
			resp.setCommandParam(respMachMessage1.getCode(),4,respMachMessage1.getMsg());
			String rc = resp.getHexStr();
			return HexUtil.decodeHex(rc);
		}
		Map<String, Integer> map1 = JSON.parseObject(JSON.toJSONString(respMachMessage1.getData()), Map.class);

		//响应结果  6个字节
		if (map1.get("flag") == 0) {
			machUpdateResultVo.setResult("00");
		} else {
			machUpdateResultVo.setResult("ff");
		}

		resp.setCommandParam(machUpdateResultVo.getHexStr());
		String rc = resp.getHexStr();
		return HexUtil.decodeHex(rc);
	}


	@Override
	public byte[] secretUpdate(TcpServiceRopo tcpServiceRopo) throws Exception {
		//要返回的对象
		TcpServiceRopo resp = new TcpServiceRopo();
		//赋返回值  全是16进制字符串
		resp.setMachId(tcpServiceRopo.getMachId());
		resp.setEdition(tcpServiceRopo.getEdition());
		resp.setType(tcpServiceRopo.getType());
		resp.setPackageNum(tcpServiceRopo.getPackageNum());
		resp.setCommandType(tcpServiceRopo.getCommandType());

		SecretUpdateVo secretUpdateVo = new SecretUpdateVo();

		Long companyId = ((Integer) redisUtil.hmGet("tcpXfMach:" + tcpServiceRopo.getMachId(), "companyId")).longValue();

		RespMachMessage respMachMessage1 = accessDeviceClient.getDecodeKey(companyId, tcpServiceRopo.getMachId(), 2);
		System.out.println(respMachMessage1);
		if (!respMachMessage1.getCode().equals("0000")) {
			resp.setCommandParam(respMachMessage1.getCode(),4,respMachMessage1.getMsg());
			String rc = resp.getHexStr();
			return HexUtil.decodeHex(rc);
		}

		KeySecret secret = JSON.parseObject(JSON.toJSONString(respMachMessage1.getData()), KeySecret.class);
		System.out.println(secret);

//        响应结果	2
//        JobID	6
		String param = "0000";
		StringBuilder stringBuilder = new StringBuilder(param);

		stringBuilder.append(NumConvertUtil.LongToHexStringNum(secret.getJobId(), 12));

		//Secret(jobId=1, code_mode=0, secret={public_key=f63a57298ee48fe8, next_public=f63a57298ee48fe8, prev_public=f63a57298ee48fe8})

		byte[] publicKey = NumConvertUtil.hexStringToByte(secret.getSecret().get("public_key"));
		byte[] nextPublicKey = NumConvertUtil.hexStringToByte(secret.getSecret().get("next_public"));
		byte[] prevPublicKey = NumConvertUtil.hexStringToByte(secret.getSecret().get("prev_public"));

		stringBuilder.append(NumConvertUtil.IntToHexStringNum(publicKey.length, 4));
		stringBuilder.append(secret.getSecret().get("public_key"));
		stringBuilder.append(NumConvertUtil.IntToHexStringNum(prevPublicKey.length, 4));
		stringBuilder.append(secret.getSecret().get("prev_public"));
		stringBuilder.append(NumConvertUtil.IntToHexStringNum(nextPublicKey.length, 4));
		stringBuilder.append(secret.getSecret().get("next_public"));

		resp.setCommandParam(stringBuilder.toString());
		String rc = resp.getHexStr();
		System.out.println(rc);
		return HexUtil.decodeHex(rc);

//
//		resp.setCommandParam(secretUpdateVo.getHexStr());
//		String rc = resp.getHexStr();
//		return HexUtil.decodeHex(rc);
	}

	@Override
	public byte[] secretUpdateResult(TcpServiceRopo tcpServiceRopo) throws Exception {
		//要返回的对象
		TcpServiceRopo resp = new TcpServiceRopo();
		//赋返回值  全是16进制字符串
		resp.setMachId(tcpServiceRopo.getMachId());
		resp.setEdition(tcpServiceRopo.getEdition());
		resp.setType(tcpServiceRopo.getType());
		resp.setPackageNum(tcpServiceRopo.getPackageNum());
		resp.setCommandType(tcpServiceRopo.getCommandType());

//		SecretUpdateResultVo secretUpdateResultVo = new SecretUpdateResultVo();
//
//		resp.setCommandParam(secretUpdateResultVo.getHexStr());
//		String rc = resp.getHexStr();
//		return HexUtil.decodeHex(rc);

		String JobID = tcpServiceRopo.getCommandParam().substring(0, 12);

		Long joblong = NumConvertUtil.HexStringToLong(JobID);



		if (!tcpServiceRopo.getCommandParam().startsWith("00", 12)) {
			resp.setCommandParam("5000",4,"未以00开头");
			String rc = resp.getHexStr();
			return HexUtil.decodeHex(rc);
		}


		Long companyId = ((Integer) redisUtil.hmGet("tcpXfMach:" + tcpServiceRopo.getMachId(), "companyId")).longValue();

		RespMachMessage respMachMessage1 = accessDeviceClient.changeKeyState(companyId, tcpServiceRopo.getMachId(), String.valueOf(joblong), 2);//
		System.out.println(respMachMessage1);
		if (!respMachMessage1.getCode().equals("0000")) {
			resp.setCommandParam(respMachMessage1.getCode(),4,respMachMessage1.getMsg());
			String rc = resp.getHexStr();
			return HexUtil.decodeHex(rc);
		}

		Map<String, Integer> map1 = JSON.parseObject(JSON.toJSONString(respMachMessage1.getData()), Map.class);

		//响应结果  6个字节
		String param = "0000";
		StringBuilder stringBuilder = new StringBuilder(param);
		if (map1.get("updataFlag") == 0) {
			stringBuilder.append("00");
		} else {
			stringBuilder.append("ff");
		}

		resp.setCommandParam(param);
		String rc = resp.getHexStr();
		System.out.println(rc);
		return HexUtil.decodeHex(rc);
	}

	@Override
	public byte[] fkParamUpdate(TcpServiceRopo tcpServiceRopo) throws Exception {
		//要返回的对象
		TcpServiceRopo resp = new TcpServiceRopo();
		//赋返回值  全是16进制字符串
		resp.setMachId(tcpServiceRopo.getMachId());
		resp.setEdition(tcpServiceRopo.getEdition());
		resp.setType(tcpServiceRopo.getType());
		resp.setPackageNum(tcpServiceRopo.getPackageNum());
		resp.setCommandType(tcpServiceRopo.getCommandType());

		FkVo fkVo = new FkVo();

		Long companyId = ((Integer) redisUtil.hmGet("tcpXfMach:" + tcpServiceRopo.getMachId(), "companyId")).longValue();


		RespMachMessage respMachMessage = payHandleFeignService.getMachFk(companyId, tcpServiceRopo.getMachId());
		if (!respMachMessage.getCode().equals("0000")) {
			resp.setCommandParam(respMachMessage.getCode(),4,respMachMessage.getMsg());
			String rc = resp.getHexStr();
			return HexUtil.decodeHex(rc);
		}

		JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(respMachMessage.getData()));


		Integer can_pay = jsonObject.getInteger("can_pay");
		Integer offline_amount = jsonObject.getInteger("offline_amount");
		Integer offline_order_num = jsonObject.getInteger("offline_order_num");
		Integer offline_time = jsonObject.getInteger("offline_time");
		Integer state_flag = jsonObject.getInteger("state_flag");
		Integer online_mode = jsonObject.getInteger("online_mode");
		String jobId = jsonObject.getString("jobId");
		JSONArray jsonArray = jsonObject.getJSONArray("identity_limit");

		if (jsonArray == null) {
			jsonArray = new JSONArray();
		}
		if (online_mode == null) {
			online_mode = 1;
		}
		if(offline_order_num==null){
			offline_order_num=0;
		}
		if(offline_time==null){
			offline_time=0;
		}
		if(offline_amount==null){
			offline_amount=0;
		}

		fkVo.setJobId(Long.toHexString(Long.valueOf(jobId)));
		fkVo.setOfflineMode(NumConvertUtil.IntToHexStringNum(online_mode, 2));
		fkVo.setOfflineAmount(NumConvertUtil.IntToHexStringNum(offline_amount, 8));
		fkVo.setOfflineOrderNum(NumConvertUtil.IntToHexStringNum(offline_order_num, 8));
		fkVo.setOfflineTime(NumConvertUtil.IntToHexStringNum(offline_time, 8));
		fkVo.setIdentityLen(NumConvertUtil.IntToHexStringNum(jsonArray.size(), 2));


		for (Object json : jsonArray) {
			JSONObject jsonObject1 = JSON.parseObject(JSON.toJSONString(json));

			Integer identity = jsonObject1.getInteger("identity");
			Integer amount = jsonObject1.getInteger("amount");
			Integer order_amount = jsonObject1.getInteger("order_amount");
			Integer order_num = jsonObject1.getInteger("order_num");

			FkUserVo fkUserVo = new FkUserVo();
			fkUserVo.setIdentity(NumConvertUtil.IntToHexStringNum(identity, 2));
			fkUserVo.setAmount(NumConvertUtil.IntToHexStringNum(amount, 8));
			fkUserVo.setOrderAmount(NumConvertUtil.IntToHexStringNum(order_amount, 8));
			fkUserVo.setOrderNum(NumConvertUtil.IntToHexStringNum(order_num, 8));

			fkVo.getList().add(fkUserVo);
		}

		log.info("Tcp_fkParamUpdate-返回【{}】 【{}】", tcpServiceRopo, fkVo);

		resp.setCommandParam(fkVo.getHexStr());
		String rc = resp.getHexStr();
		return HexUtil.decodeHex(rc);
	}

	@Override
	public byte[] fkParamUpdateResult(TcpServiceRopo tcpServiceRopo) throws Exception {
		//要返回的对象
		TcpServiceRopo resp = new TcpServiceRopo();
		//赋返回值  全是16进制字符串
		resp.setMachId(tcpServiceRopo.getMachId());
		resp.setEdition(tcpServiceRopo.getEdition());
		resp.setType(tcpServiceRopo.getType());
		resp.setPackageNum(tcpServiceRopo.getPackageNum());
		resp.setCommandType(tcpServiceRopo.getCommandType());

		FkResultVo fkResultVo = new FkResultVo();

		Long companyId = ((Integer) redisUtil.hmGet("tcpXfMach:" + tcpServiceRopo.getMachId(), "companyId")).longValue();


		String JobId = tcpServiceRopo.getCommandParam().substring(0, 12);


		if (!tcpServiceRopo.getCommandParam().startsWith("00", 12)) {
			resp.setCommandParam("0000ff");
			String rc = resp.getHexStr();
			return HexUtil.decodeHex(rc);
		}


		RespMachMessage changeFkState = payHandleFeignService.changeFkState(companyId, tcpServiceRopo.getMachId(), String.valueOf(Long.parseLong(JobId, 16)));
		if (!changeFkState.getCode().equals("0000")) {
			resp.setCommandParam(changeFkState.getCode(),4,changeFkState.getMsg());
			String rc = resp.getHexStr();
			return HexUtil.decodeHex(rc);
		}

		Map<String, Integer> map1 = JSON.parseObject(JSON.toJSONString(changeFkState.getData()), Map.class);
		//响应结果  6个字节
		if (map1.get("flag") == 0) {
			fkResultVo.setFlag("00");
		} else {
			fkResultVo.setFlag("ff");
		}

		resp.setCommandParam(fkResultVo.getHexStr());
		log.info("Tcp_fkParamUpdateResult-返回【{}】 【{}】", tcpServiceRopo, fkResultVo);

		String rc = resp.getHexStr();
		return HexUtil.decodeHex(rc);
	}

	@Override
	public byte[] whiteList(TcpServiceRopo tcpServiceRopo) throws Exception {
		//要返回的对象
		TcpServiceRopo resp = new TcpServiceRopo();
		//赋返回值  全是16进制字符串
		resp.setMachId(tcpServiceRopo.getMachId());
		resp.setEdition(tcpServiceRopo.getEdition());
		resp.setType(tcpServiceRopo.getType());
		resp.setPackageNum(tcpServiceRopo.getPackageNum());
		resp.setCommandType(tcpServiceRopo.getCommandType());

		WhiteListVo whiteListVo = new WhiteListVo();

		//全量白名单组号
		String groupNo = tcpServiceRopo.getCommandParam().substring(0, 8);
		String res = tcpServiceRopo.getCommandParam().substring(8, 10);
		Integer num = NumConvertUtil.HexStringToInt(res);

		whiteListVo.setGroupNo(groupNo);

		Long companyId = ((Integer) redisUtil.hmGet("tcpXfMach:" + tcpServiceRopo.getMachId(), "companyId")).longValue();

		int listLimit = 1;
		if (num != 0) {
			listLimit = num;
		}
//		listLimit = 1;

		Map<String, Object> map = new HashMap<>();
		map.put("companyID", companyId);
		map.put("machNo", tcpServiceRopo.getMachId());
		map.put("listFormat", 2);
		map.put("listLimit", listLimit);

		RespMachMessage changeWhiteListState = payHandleFeignService.changeWhiteListState(map);
		if (!changeWhiteListState.getCode().equals("0000")) {
			log.info("Tcp_whiteList-异常 【{}】 【{}】", tcpServiceRopo, changeWhiteListState);
			resp.setCommandParam("5000",4,changeWhiteListState.getMsg());
			String rc = resp.getHexStr();
			return HexUtil.decodeHex(rc);
		}

		JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(changeWhiteListState.getData()));


		Integer flag = jsonObject.getInteger("flag");
		Integer model = jsonObject.getInteger("model");
		JSONArray jsonArray = jsonObject.getJSONArray("list");

		Integer size = 0;
		if (jsonArray != null) {
			size = jsonArray.size();
		}

		whiteListVo.setBlackSum(NumConvertUtil.IntToHexStringNum(size, 2));

		/**
		 * flag	操作标志	Int	1-删除，2-添加
		 * model	全量/增量标志	Int	0-全量，1-增量
		 */
		if (flag == null) {
			whiteListVo.setBlackAndWhite("02");
		} else if (flag == 2) {
			whiteListVo.setBlackAndWhite("02");
		} else {
			whiteListVo.setBlackAndWhite("01");
		}

		if (model == null) {
			whiteListVo.setModel("01");
		} else if (model == 0) {
			whiteListVo.setModel("00");
		} else {
			whiteListVo.setModel("01");
		}
		if (jsonArray != null) {
			for (Object json : jsonArray) {
				JSONObject jsonObject1 = JSON.parseObject(JSON.toJSONString(json));
				WhiteUserVo whiteUserVo = new WhiteUserVo();
				if(jsonObject1.getString("card_No")==null){
					whiteUserVo.setCardNo("00000000");
				}else {
					whiteUserVo.setCardNo(jsonObject1.getString("card_No"));
					if(jsonObject1.getInteger("cardstate")!=null && jsonObject1.getInteger("cardstate")!=1){
						whiteUserVo.setCardNo("00000000");
					}
					if(!jsonObject1.getString("card_No").matches("^[0-9a-fA-F]+$")){
						whiteUserVo.setCardNo("00000000");
					}
					if(jsonObject1.getString("card_No").length()!=8){
						whiteUserVo.setCardNo("00000000");
					}
				}

				if (jsonObject1.getInteger("cardType") != null) {
					whiteUserVo.setCardType(
							NumConvertUtil.IntToHexStringNum(jsonObject1.getInteger("cardType"), 2));
				}
				if (jsonObject1.getInteger("P_ID") == null) {
					continue;
				}
				whiteUserVo.setPId(NumConvertUtil.IntToHexStringNum(jsonObject1.getInteger("P_ID"), 8));
				whiteListVo.getList().add(whiteUserVo);
			}
		}

		log.info("Tcp_whiteList-返回【{}】 【{}】", tcpServiceRopo, whiteListVo);

		resp.setCommandParam(whiteListVo.getHexStr());
		String rc = resp.getHexStr();
		return HexUtil.decodeHex(rc);
	}

	@Override
	public byte[] whiteListResult(TcpServiceRopo tcpServiceRopo) throws Exception {
		//要返回的对象
		TcpServiceRopo resp = new TcpServiceRopo();
		//赋返回值  全是16进制字符串
		resp.setMachId(tcpServiceRopo.getMachId());
		resp.setEdition(tcpServiceRopo.getEdition());
		resp.setType(tcpServiceRopo.getType());
		resp.setPackageNum(tcpServiceRopo.getPackageNum());
		resp.setCommandType(tcpServiceRopo.getCommandType());

		WhiteListResultVo whiteListResultVo = new WhiteListResultVo();

		if (!tcpServiceRopo.getCommandParam().startsWith("00")) {
			resp.setCommandParam("5000",4,"未以00开头");
			String rc = resp.getHexStr();
			return HexUtil.decodeHex(rc);
		}

		Long companyId = ((Integer) redisUtil.hmGet("tcpXfMach:" + tcpServiceRopo.getMachId(), "companyId")).longValue();

		Map<String, Object> map = new HashMap<>();
		map.put("result", NumConvertUtil.HexStringToInt(tcpServiceRopo.getCommandParam()));
		map.put("companyID", companyId);
		map.put("machNo", tcpServiceRopo.getMachId());

		RespMachMessage xfWhiteListResult = payHandleFeignService.getXFWhiteListResult(map);
		if (!xfWhiteListResult.getCode().equals("0000")) {
			resp.setCommandParam(xfWhiteListResult.getCode(),4,xfWhiteListResult.getMsg());
			String rc = resp.getHexStr();
			return HexUtil.decodeHex(rc);
		}

		JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(xfWhiteListResult.getData()));
		//0xff：有；0x00：无
		//底层 flag	后续更新标识	Int	0xff：有；0x00：无
		Integer flag = jsonObject.getInteger("flag");
		if (flag == 0) {
			whiteListResultVo.setFlag("00");
		} else {
			whiteListResultVo.setFlag("ff");
		}

		resp.setCommandParam(whiteListResultVo.getHexStr());

		log.info("Tcp_whiteListResult-返回【{}】 【{}】", tcpServiceRopo, whiteListResultVo);

		String rc = resp.getHexStr();
		return HexUtil.decodeHex(rc);
	}


//	public static void main(String[] args){
//		String JobID = "1676527443175";
//
//		Long joblong = NumConvertUtil.HexStringToLong(JobID);
//		System.out.println(joblong);
//	}

}
